/**
 * @FileName: DBLApplication.java
 * @Package:com.bdtop.dbl
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 * @version V1.0
 */

package com.bdtop.dbl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.litepal.LitePalApplication;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
import com.bdtop.dbl.db.model.RecordInfo;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.Preferences;

/**
 * @ClassName: DBLApplication
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 */
public class DBLApplication extends LitePalApplication {

	public List<Activity> activityList = new LinkedList<Activity>();
	private static DBLApplication instance;

	// public Boolean isNeedRefreshList = true;
	//
	// public String currentDeviceName ;
	// public String currentDeviceMdn;

	public ArrayList<DeviceInfo> deviceInfoList;
	public DeviceInfo currentDi;
	// 2015 new api 位置信息与  获取全部内容分离   [记录 百度位置]
	private Map<String, String> addressInfo = new HashMap<String, String>();
	public String getAddressInfoByMdn(String mdn){
		return addressInfo.get(mdn);
	}
	public void setAddressInfoByMdn(String mdn, String address){
		addressInfo.put(mdn, address);
	}
	
	public boolean firstFlag_LoginButNoDevice = true;

	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		// Baidu map initialize
		SDKInitializer.initialize(getApplicationContext());

		mLocationClient = new LocationClient(getApplicationContext());
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll");
		option.setScanSpan(10000);
		option.setOpenGps(true);
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
		mLocationClient.start();

		CrashHandler.getInstance().setCustomCrashHanler(instance);

		Connector.getDatabase(); // init litepal

		initAppRecordInfo();
	}
	
	private void initAppRecordInfo() {
		if (DataSupport.findAll(RecordInfo.class).size() < 1) {
			DBLDebug.logd("db first init model : record info");
			RecordInfo recordInfo = new RecordInfo();
			recordInfo.save();
		} else {
			DBLDebug.logi("db check ! model : record info ok");
		}
	}

	public static synchronized DBLApplication getInstance() {
		return instance;
	}

	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	public void remove(Activity activity) {
		activityList.remove(activity);
	}

	public void exit() {

		Preferences.saveLoginStatus(this, false);
		
		if(currentDi != null){
			Preferences.saveLastSelectedDevice(currentDi.mdn);
		}

		for (Activity activity : activityList) {
			activity.finish();
		}
		
		DBLDebug.logd("app 挂机时间恢复重新计算");
		Preferences.saveGuaQiTime(0);

		if (null != activityList && activityList.size() > 0) {
//			System.exit(0);
		}
	}

	public boolean isAppLife() {
		return activityList.size() > 0;
	}

	private MyLocationListener mMyLocationListener;
	private LocationClient mLocationClient;

	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			DBLDebug.logi("self location has receive");
			mLocationClient.stop();
			mLocationClient.unRegisterLocationListener(mMyLocationListener);

			if (location.getCityCode() == null) {
				DBLDebug.loge("!手机位置定位失败!");
				return;
			}

			Preferences.saveLastSelfLocation(getApplicationContext(),
					new String[] { String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()) });

			// fix: 一次性commit
			 Preferences.saveLastCityCode(getApplicationContext(),
			 location.getCityCode());
			 Preferences.saveLocationInfo(getApplicationContext(),
			 location.getAddrStr());
//			Editor editor = Preferences.getPreferences(getApplicationContext()).edit();
//			editor.putString(Preferences.SELF_CITY_CODE, location.getCityCode());
//			editor.putString(Preferences.SELF_LOCATION_INFO, location.getAddrStr());
//			editor.commit();
		}
	}

	public void startLocationClient(BDLocationListener listener) {
		mLocationClient.registerLocationListener(listener);
		mLocationClient.start();
	}

	public void stopLocationClient(BDLocationListener listener) {
		mLocationClient.stop();
		mLocationClient.unRegisterLocationListener(listener);
	}

}
